package com.favorites.common;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.favorites.vo.RequestWithCookie;
import com.favorites.vo.TouTiao;
import com.favorites.vo.TouTiaoBlog;
import com.sun.media.sound.SoftTuning;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import sun.nio.ch.Net;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by
 *
 * @author dw
 * @date 2018/04/04
 */
@Service
public class ParseFavorites extends ParseBase {
    private static final Logger logger = LoggerFactory.getLogger(ParseFavorites.class);

    /**
     * beforYear过滤日期以前的收藏信息
     *
     * @param beforYear
     */
    public void parse2File(String beforYear) {
        Map<String, RequestWithCookie> favoritesMap = getFavoritesSetting();

        favoritesMap.forEach((key, value) -> {
            logger.debug("解析key:" + key);
            switch (key) {
                case "toutiao_shoucang":
                    parseJson2File(value, beforYear);
                    break;
                case "oschina":
                    parseHtml(value);
                    break;
                default:
                    logger.error("默认解析器");
            }
        });
    }

    /**
     * beforYear过滤日期以前的收藏信息
     *
     * @param beforYear
     */
    public List<TouTiaoBlog> parseAndBackJson(String beforYear) {
        Map<String, RequestWithCookie> favoritesMap = getFavoritesSetting();
        List<TouTiaoBlog> back = new ArrayList<TouTiaoBlog>();

        favoritesMap.forEach((key, value) -> {
            logger.debug("解析key:" + key);
            switch (key) {
                case "toutiao_shoucang":
                    back.addAll(parseJson2Back(value, beforYear));
                    break;
//                case "toutiao_guolv":
//                    back.addAll(parseJson2Back(value, beforYear));
//                    break;
                case "oschina":
                    parseHtml(value);
                    break;
            }
        });
        logger.info("数据解析完毕:{}", back.size());
        return back;
    }


    private void parseJson2File(RequestWithCookie value, String beforYear) {
        List<TouTiaoBlog> datesUse = getDataFromToutiao(value, beforYear);
        FreemakerUtils.makeFieByFtl("toutiao_markdown.ftl", datesUse);
    }

    private List<TouTiaoBlog> parseJson2Back(RequestWithCookie value, String beforYear) {
        List<TouTiaoBlog> datesUse = getDataFromToutiao(value, beforYear);
        return datesUse;
    }

    private void parseHtml(RequestWithCookie value) {
        logger.debug("parseHtml...");
    }

}
